﻿<template>
  <van-popup v-model="visible" position="bottom" closeable>
    <van-form @submit="handleSubmit" :loading="loading">
      <van-field
        v-model="formFields.LinkName"
        name="LinkName"
        label="连接名"
        :rules="[{ required: true, message: '必填' }]"
      />
      <van-field
        v-model="formFields.ConnectionStr"
        name="ConnectionStr"
        label="连接字符串"
        :rules="[{ required: true, message: '必填' }]"
      />
      <VanFieldSelectPicker
        name="DbType"
        label="数据库类型"
        v-model="formFields.DbType"
        :columns="DbTypeList"
        :option="option"
      />
      <div style="margin: 16px;">
        <van-button block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </van-popup>
</template>

<script>
import {
  Base_DbLink_GetTheData,
  Base_DbLink_SaveData
} from "@/api/Base_Manage/Base_DbLink";
import { mapGetters } from "vuex";
import VanFieldSelectPicker from "@/components/VanField/VanFieldSelectPicker";

export default {
  props: {
    afterSubmit: {
      type: Function,
      default: null
    }
  },
  components: {
    VanFieldSelectPicker
  },
  data() {
    return {
      visible: false,
      loading: false,
      formFields: {
        LinkName: "",
        ConnectionStr: "",
        DbType: ""
      },
      entity: {},
      option: {
        label: "label",
        value: "value"
      },
      DbTypeList: [
        { label: "SqlServer", value: "SqlServer" },
        { label: "MySql", value: "MySql" },
        { label: "Oracle", value: "Oracle" },
        { label: "PostgreSql", value: "PostgreSql" }
      ]
    };
  },
  computed: {
    ...mapGetters(["hasPerm"])
  },

  methods: {
    add() {
      this.entity = {};
      this.visible = true;
      this.formFields = {
        LinkName: "",
        ConnectionStr: "",
        DbType: ""
      };
    },
    edit(id) {
      this.visible = true;
      this.$nextTick(() => {
        this.formFields = {
          LinkName: "",
          ConnectionStr: "",
          DbType: ""
        };

        Base_DbLink_GetTheData({ id: id }).then(resJson => {
          this.entity = resJson.Data;
          Object.keys(this.formFields).forEach(item => {
            this.formFields[item] = this.entity[item];
          });
        });
      });
    },

    handleSubmit(value) {
      this.entity = Object.assign(this.entity, this.formFields);
      this.loading = true;
      Base_DbLink_SaveData(this.entity).then(resJson => {
        this.loading = false;

        if (resJson.Success) {
          this.$toast("操作成功");
          this.afterSubmit();
          this.visible = false;
        } else {
          this.$toast(resJson.Msg);
        }
      });
    }
  }
};
</script>
